package com.xiefengf.rabbitmq.producer.service;

import cn.hutool.json.JSONUtil;
import com.xiefengf.rabbitmq.producer.utils.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * @author xiefengf
 * @version 1.0
 * @date 2024/1/21 17:38
 *
 * 过期时间ttl队列和消息
 */
@Service
public class TtlProductService {

    @Resource(name = "RabbitTemplate")
    private RabbitTemplate rabbitTemplate;

    /**
     * 队列设置过期时间、消息也设置过期时间
     * @param userId
     * @param productId
     * @param msg
     */
    public void makeOrder1(Integer userId,Integer productId,String msg){
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId",userId);
        map.put("productId",productId);
        map.put("product_ttl_1_msg",msg);
        rabbitTemplate.convertAndSend(StringUtils.DIRECT_TTL_EXCHANGE_NAME,StringUtils.DIRECT_TTL_KEY_1, JSONUtil.toJsonStr(map));
    }

    /**
     * 消息设置过期时间
     * @param userId
     * @param productId
     * @param msg
     */
    public void makeOrder2(Integer userId,Integer productId,String msg){
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId",userId);
        map.put("productId",productId);
        map.put("product_ttl_2_msg",msg);
        // 设置消息的参数
//        MessagePostProcessor messagePostProcessor =  new MessagePostProcessor(){
//            @Override
//            public Message postProcessMessage(Message message) throws AmqpException {
//                message.getMessageProperties().setExpiration("15000");
//                message.getMessageProperties().setContentEncoding("UTF-8");
//                return message;
//            }
//        };
        // Expiration字段以微秒为单位表示TTL值,且与x-message-ttl具有相同的约束条件.因为Expiration字段必须是字符串类型,borker将只会接收以字符串形式表达的数字
        // 当同时指定了queue和message中的TTL值,两者中较小的值将会起作用
        MessageProperties messageProperties = new MessageProperties();
        // 过期时间
        messageProperties.setExpiration("15000");
        // 设置此条消息持久化
        messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
        // 设置消息优先级
        messageProperties.setPriority(10);
        // 消息JSON转换
        Message message = new Message(JSONUtil.toJsonStr(map).getBytes(),messageProperties);
        // 发送消息
        rabbitTemplate.convertAndSend(StringUtils.DIRECT_TTL_EXCHANGE_NAME,StringUtils.DIRECT_TTL_KEY_2,message);
    }


}
